package cn.texous.web.parsing.book.common.utils;

import cn.texous.util.commons.util.upgrade.Optional;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * insert description here
 *
 * @author Showa.L
 * @since 2019/7/25 11:47
 */
@Slf4j
public class AnaFileUtils {

    public static final String load(String fileName) {
        return load(AnaFileUtils.class.getClassLoader().getResourceAsStream(fileName));
    }

    /**
     * 读取文件
     *
     * @param file file
     * @return
     */
    public static final String load(File file) {
        try {
            return load(new FileInputStream(file));
        } catch (FileNotFoundException e) {
            log.error("File Not Found Exception", e);
        }
        return null;
    }

    /**
     * 读取文件
     *
     * @param is inputstream
     * @return
     */
    public static final String load(InputStream is) {
        try (InputStream inputStream = is) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String str = null;
            StringBuilder sb = new StringBuilder();
            while ((str = reader.readLine()) != null) {
                sb.append(str);
            }
            String content = sb.toString();
            return content;
        } catch (Exception e) {
            log.error("读取文件失败", e);
        }
        return null;
    }

    /**
     * 获取 classpath 下的文件
     *
     * @param fileName 文件名 origin/fiction.json
     * @return
     */
    public static final String loadPathFile(String fileName) {
        InputStream inputStream = AnaFileUtils.class
                .getClassLoader().getResourceAsStream(fileName);
        return Optional.ofNullable(inputStream)
                .map(AnaFileUtils::load)
                .orElse(null);
    }

    public static final String getPath() {
        String path = AnaFileUtils.class.getClassLoader().getResource("").getPath();
        log.info("get AnaFileUtils path: {}", path);
        return path;
    }

    public static void main(String[] args) {

    }

}
